package apps.sim.action.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Map;

import apps.sim.Index;
import apps.sim.core.AExtendedHandler;
import apps.sim.util.ContentTypes;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

public class FolderShareHandler extends AExtendedHandler {
	private FolderShareConfig folderShareConfig = new FolderShareConfig();

	@Override
	public void handleResponse(HttpExchange exchange, String context) throws Exception {
		final Map<String, String> extractParams = Util.extractParams(exchange.getRequestURI());
		final String string = extractParams.get("file");
		String sub = string != null ? string : "";
		final String shareFolder = folderShareConfig.getShareFolder();
		final File dir = new File(shareFolder + sub);
		if (!dir.exists()) {
			throw new Exception("Please configure a folder to share via <img src=\"" + Index.getCurrentAddress() + "/simulate/global/src?src=http/img/settings.png\"/> icon");
		}
		if (!dir.isFile()) {
			final File[] files = dir.listFiles();
			final StringBuilder builder = new StringBuilder();
			builder.append("<html>");
			builder.append("<body>");
			builder.append("	<table>");
			builder.append("		<tr>");
			builder.append("			<td style=\"width:50px;\"></td>");
			builder.append("			<td>");
			builder.append("				<h1>Folder : " + sub + "</h1></td>");
			builder.append("		</tr>");
			builder.append("		<tr>");
			builder.append("			<td></td>");
			builder.append("			<td><hr />");
			builder.append("			</td>");
			builder.append("		</tr>");
			for (File file : files) {
				final String name = file.getName();
				builder.append("		<tr>");
				builder.append("			<td></td>");
				builder.append("			<td>");
				builder.append("<a href=\"" + context + "?file=" + sub + "/" + name + "\">");
				builder.append(name);
				builder.append("</a>");
				builder.append("			</td>");
				builder.append("		</tr>");

			}
			builder.append("	</table>");
			builder.append("</body>");
			builder.append("</html>");

			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", getContentType());
			exchange.sendResponseHeaders(200, 0);
			OutputStream responseBody = exchange.getResponseBody();
			responseBody.write(builder.toString().getBytes());
			responseBody.flush();
			responseBody.close();
		} else {
			Headers responseHeaders = exchange.getResponseHeaders();
			final String substring = dir.getName().substring(dir.getName().lastIndexOf(".") + 1);
			final String contentType = ContentTypes.getContentType("." + substring);
			responseHeaders.set("Content-Type", contentType);
			exchange.sendResponseHeaders(200, 0);
			OutputStream responseBody = exchange.getResponseBody();
			FileInputStream in = null;
			try {
				in = new FileInputStream(dir);
				int i = 0;
				while ((i = in.read()) != -1) {
					responseBody.write(i);
				}
			} finally {
				if (in != null) {
					in.close();
				}
			}
			responseBody.flush();
			responseBody.close();

		}

	}

	@Override
	public String getContentType() {
		return "text/html;charset=utf-8";
	}

	@Override
	public String getDescription() {
		return "Share a folder over HTTP";
	}

	@Override
	public IHandlerConfig getHandlerConfiguration() {
		return folderShareConfig;
	}

	@Override
	public void setHandlerConfiguration(IHandlerConfig folderShareConfig) {
		this.folderShareConfig = (FolderShareConfig) folderShareConfig;
	}

	public static class FolderShareConfig implements IHandlerConfig {
		private String shareFolder;

		public byte[] checkIfFolderPresent() {
			return String.valueOf(" Folder exists: " + new File(shareFolder != null ? shareFolder : "").exists()).getBytes();
		}

		public String getShareFolder() {
			return shareFolder;
		}

		@Config(descrition = "Configure the folder to share")
		public void setShareFolder(String shareFolder) {
			this.shareFolder = shareFolder;
		}

		@Override
		public String asString() {
			return shareFolder != null ? shareFolder : "";
		}

		@Override
		public void fromString(String string) {
			this.shareFolder = (string != null && !"".equals(string) ? string : null);
		}

		@Override
		public IHandlerConfig cloneInstance() {
			final FolderShareConfig config = new FolderShareConfig();
			config.setShareFolder(this.getShareFolder());
			return config;
		}
	}

}
